package com.hmyd.hmyd_android.view.ad;

import java.util.Timer;
import java.util.TimerTask;

import com.hmyd.hmyd_android.R;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.SpinnerAdapter;

/**
 * 自动轮播
 * 
 **/
public class AutoGallery extends Gallery implements OnItemSelectedListener, OnItemClickListener,
		OnItemLongClickListener {

	private int mTime;// 轮播时间
	private int mItemWidth;// 子控件的宽度
	private int mItemHeight;// 子控件的高度
	private int mItemRes;// 子控件的分辨率
	private int mItemLoadingResID;// 子控件的加载图片的Id
	private int mItemLayout;// 子控件布局
	private float mDivUnSelectedAlpha = 1.0f;

	private static final int TIMER_STATE_RUN = 0;
	private static final int TIMER_STATE_CANCEL = 1;
	private int mTimerState = TIMER_STATE_RUN;
	private boolean mIsLoop = true;// 循环播放
	private boolean mIsAuto = true;// 是否自动播放
	private OnItemSelectedListener mListener;
	private OnItemClickListener mChickListener;
	private OnItemLongClickListener mLongClickListener;
	private boolean onChangeSelected = false;// 无限循环的最后一个与第一个跳转

	/**
	 * 获取子控件基础宽度
	 * */
	public int getItemWidth() {
		return mItemWidth;
	}

	/**
	 * 获取子控件基础高度
	 * */
	public int getItemHeight() {
		return mItemHeight;
	}

	/**
	 * 获取子控件基础分辨率
	 * */
	public int getItemRes() {
		return mItemRes;
	}

	/**
	 * 获取子控件加载底图
	 * */
	public int getItemLoadingResID() {
		return mItemLoadingResID;
	}

	/**
	 * 获取子控件加载底图
	 * */
	public int getItemLayout() {
		return mItemLayout;
	}

	private static final int TIMERANIMATION = 1;
	private static final int SPACEING = 2;
	private SlideListener mSlideListener;
	private PointView mPointView;

	private final Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIMERANIMATION:
				int position = getSelectedItemPosition();
				int mCount = 1;
				AutoGalleryAdapter mTemp = (AutoGalleryAdapter) getAdapter();
				if (mTemp != null)
					mCount = mTemp.getListCount();
				if (mCount == 0)
					return;
				int mIndex = position % mCount;
				if (mSlideListener != null) {
					if (mIndex >= mCount - 1) {
						mSlideListener.onMoveSelect(0);
					} else {
						mSlideListener.onMoveAction(KeyEvent.KEYCODE_DPAD_RIGHT);
					}
				}

				if (position >= (getCount() - 1)) {
					AutoGallery.this.setSelection(0, true);
				} else {
					onScroll(null, null, SPACEING, 0);
					onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
				}

				break;
			default:
				break;
			}
		};

	};

	private Timer timer;
	private TimerTask task;

	public AutoGallery(Context context) {
		this(context, null);
	}

	public AutoGallery(Context context, AttributeSet attrs) {
		this(context, attrs, R.style.DivAutoGallery);
	}

	@SuppressWarnings("deprecation")
	public AutoGallery(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		final Resources res = getResources();
		final int itemWidth = res.getInteger(R.integer.ag_item_width_default);
		final int itemHeight = res.getInteger(R.integer.ag_item_height_default);
		final int itemRes = res.getInteger(R.integer.ag_item_res_default);
		final int defaultTime = res.getInteger(R.integer.ag_time_default);

		// Retrieve styles attributes
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoGallery, defStyle, 0);
		mItemWidth = a.getInt(R.styleable.AutoGallery_ag_item_width, itemWidth);
		mItemHeight = a.getInt(R.styleable.AutoGallery_ag_item_height, itemHeight);
		mItemRes = a.getInt(R.styleable.AutoGallery_ag_item_res, itemRes);
		mTime = a.getInt(R.styleable.AutoGallery_ag_time, defaultTime);
		mItemLoadingResID = a.getResourceId(R.styleable.AutoGallery_ag_item_loading_bg,
				R.drawable.view_no_photo);
		mItemLayout = a.getResourceId(R.styleable.AutoGallery_ag_item_layout,
				R.layout.view_autogallery_item);
		mDivUnSelectedAlpha = a.getFloat(R.styleable.AutoGallery_unselectedalpha, 1.0f);
		mIsLoop = a.getBoolean(R.styleable.AutoGallery_ag_loop, true);
		mIsAuto = a.getBoolean(R.styleable.AutoGallery_ag_auto, true);

		setUnselectedAlpha(mDivUnSelectedAlpha);
		onRestart();
		a.recycle();
		super.setOnItemSelectedListener(this);
		super.setOnItemClickListener(this);
		super.setOnItemLongClickListener(this);
	}

	/**
	 * 引导点模式
	 * */
	public void initPointView(Activity mActivity) {

		initPointView(mActivity, null);

	}

	/**
	 * 引导点模式
	 * */
	public void initPointView(Activity mActivity, int mGravity) {

		initPointView(mActivity, null, mGravity);

	}

	/**
	 * 引导点模式
	 * */
	public void initPointView(Activity mActivity, View mView) {
		initPointView(mActivity, mView, -1);
	}

	/**
	 * 引导点模式
	 * */
	public void initPointView(Activity mActivity, View mView, int mGravity) {

		if (mView != null)
			mPointView = (PointView) mView.findViewById(R.id.pointview);
		else
			mPointView = (PointView) mActivity.findViewById(R.id.pointview);
		if (mPointView == null)
			return;
		AutoGalleryAdapter mAdapter = (AutoGalleryAdapter) getAdapter();
		if (mAdapter != null) {
			mPointView.setTotalPage(mAdapter.getListCount());
			mPointView.requestLayout();
		}
		if (mGravity != -1) {
			mPointView.setGravity(mGravity);
		}
	}

	@Override
	public void setAdapter(SpinnerAdapter mAdapter) {
		AutoGalleryAdapter mTemp = (AutoGalleryAdapter) mAdapter;
		if (mTemp != null) {
			mTemp.setLoop(mIsLoop);
			if (mPointView != null) {
				mPointView.setTotalPage(mTemp.getListCount());
				mPointView.requestLayout();
			}
		}
		super.setAdapter(mAdapter);
		setSelection(0);
	}

	@Override
	public void setSelection(int mSelection) {

		AutoGalleryAdapter mAdapter = (AutoGalleryAdapter) AutoGallery.this.getAdapter();
		if (mAdapter != null && mAdapter.isLoop()) {
			super.setSelection(Integer.MAX_VALUE / 2 / mAdapter.getListCount()
					* mAdapter.getListCount() + mSelection);
		} else
			super.setSelection(mSelection);
	}

	public int getSelectedPosition() {
		AutoGalleryAdapter mAdapter = (AutoGalleryAdapter) getAdapter();
		if (mAdapter != null) {
			boolean mIsLoop = mAdapter.isLoop();
			int mIndex = super.getSelectedItemPosition();
			if (mIsLoop) {
				return mIndex % mAdapter.getListCount();
			}
		}
		return super.getSelectedItemPosition();
	}

	/**
	 * 滑动同步接口
	 * */
	public void setSlideListener(SlideListener mSlideListener) {

		this.mSlideListener = mSlideListener;
	}

	@Override
	public void setOnItemSelectedListener(OnItemSelectedListener mListener) {

		this.mListener = mListener;

	}

	@Override
	public void setOnItemClickListener(OnItemClickListener mChickListener) {

		this.mChickListener = mChickListener;

	}

	@Override
	public void setOnItemLongClickListener(OnItemLongClickListener listener) {
		this.mLongClickListener = listener;
	}

	private boolean isScrollingLeft(MotionEvent paramMotionEvent1, MotionEvent paramMotionEvent2) {
		float f2 = paramMotionEvent2.getX();
		float f1 = paramMotionEvent1.getX();
		if (f2 > f1)
			return true;
		return false;
	}

	@Override
	public boolean onFling(MotionEvent paramMotionEvent1, MotionEvent paramMotionEvent2,
			float paramFloat1, float paramFloat2) {
		int keyCode;
		if (isScrollingLeft(paramMotionEvent1, paramMotionEvent2)) {
			keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
		} else {
			keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
		}
		onKeyDown(keyCode, null);
		if (mSlideListener != null) {
			mSlideListener.onFlingAction(keyCode);
		}

		AutoGalleryAdapter mAdapter = (AutoGalleryAdapter) AutoGallery.this.getAdapter();
		if (mAdapter != null && mAdapter.isLoop()) {
			int mIndex = getSelectedPosition();
			int mCount = mAdapter.getListCount();
			if (mIndex == mCount - 1 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
				onChangeSelected = true;
			else if (mIndex == 0 && keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
				onChangeSelected = true;
			else
				onChangeSelected = false;
		} else {
			onChangeSelected = false;
		}

		return true;
	}

	public void onRestart() {
		mTimerState = TIMER_STATE_RUN;
		if (mIsAuto) {
			timer = new Timer();
			task = new TimerTask() {
				public void run() {
					mHandler.sendEmptyMessage(TIMERANIMATION);
				}
			};
			timer.schedule(task, mTime, mTime);
		}
	}

	public void onDestroy() {
		mTimerState = TIMER_STATE_CANCEL;
		if (mIsAuto && task != null && timer != null) {
			task.cancel();
			timer.cancel();
			timer = null;
		}
	}

	/**
	 * 强制停止轮播
	 * */
	public void onStop() {
		onDestroy();
		mIsAuto = false;
	}

	/**
	 * 强制开启轮播
	 * */
	public void onStart() {
		mIsAuto = true;
		onRestart();

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (mSlideListener != null)
				mSlideListener.onMoveSelect(getSelectedPosition());
		}

		if ((event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
				&& mTimerState == TIMER_STATE_RUN) {
			onDestroy();
		} else if (event.getAction() == MotionEvent.ACTION_UP && mTimerState == TIMER_STATE_CANCEL) {
			onRestart();
		}
		return super.onTouchEvent(event);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

		if (mListener != null) {
			mListener.onItemSelected(arg0, arg1, getSelectedPosition(), arg3);
		}
		if (onChangeSelected && mSlideListener != null) {
			mSlideListener.onMoveSelect(getSelectedPosition());
		}

		if (mPointView != null) {
			mPointView.setCurrentPage(getSelectedPosition());
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		if (mListener != null) {
			mListener.onNothingSelected(arg0);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

		if (mChickListener != null) {
			mChickListener.onItemClick(arg0, arg1, getSelectedPosition(), arg3);
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (mLongClickListener != null) {
			return mLongClickListener.onItemLongClick(arg0, arg1, getSelectedPosition(), arg3);
		}
		return false;
	}

	public int getPointViewWidth() {
		return mPointView.layoutWidth;
	}

}
